package com.educate.device.rpc.provide.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.educate.common.utils.converter.ListUtils;
import com.educate.common.utils.exception.AppException;
import com.educate.common.web.BeanUtils;
import com.educate.device.dao.ChildDeviceDao;
import com.educate.device.model.bo.ChildDeviceBO;
import com.educate.device.model.po.ChildDevice;
import com.educate.device.rpc.api.ChildDeviceService;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

@Log4j2
@Service(
        version = "${api.service.version}",
        application = "${dubbo.application.id}",
        protocol = "${dubbo.protocol.id}",
        registry = "${dubbo.registry.id}"
)
public class ChildDeviceServiceImpl implements ChildDeviceService {

    @Resource ChildDeviceDao childDeviceDao;

    @Override
    public void create(ChildDeviceBO bo) {
        childDeviceDao.insert(bo);
    }

    @Override
    public void delete(ChildDeviceBO bo) {
        childDeviceDao.delete(bo);
    }

    @Override
    public void delete(String childDeviceId) {
        childDeviceDao.deleteById(childDeviceId);
    }

    @Override
    public ChildDeviceBO detail(String childDeviceId) {
        Optional<ChildDevice> optional = childDeviceDao.findById(childDeviceId);
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        return new ChildDeviceBO(optional.get());
    }

    @Override
    public ChildDeviceBO detail(ChildDeviceBO bo) {
//        return detail(bo.getOrganizationId());
        return null;
    }

    @Override
    public void update(ChildDeviceBO bo) {
        Optional<ChildDevice> optional = childDeviceDao.findById(bo.getChildDeviceId());
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        BeanUtils.copyPropertiesNonEmpty(bo, optional.get());
        childDeviceDao.save(optional.get());
    }

    @Override
    public Page<ChildDeviceBO> query(ChildDeviceBO bo, PageRequest pageRequest) {
        return childDeviceDao.query(bo, pageRequest).map(ChildDeviceBO::new);
    }

    @Override
    public List<ChildDeviceBO> list(ChildDeviceBO bo) {
        List<ChildDevice> result = childDeviceDao.findAll();
        return ListUtils.map(result, ChildDeviceBO::new);
    }
}
